package com.launch.carmanager.common.base;

import android.support.annotation.StringRes;

import org.greenrobot.eventbus.EventBus;

import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by ganquan on 2019/3/28 11:09
 */
public class BasePresenter<V extends BaseView> {
    private CompositeSubscription mSubscriptions;

    protected V mView;

    public BasePresenter(V mView) {
        this.mView = mView;
    }

    protected void alert(CharSequence msg) {
        mView.alert(msg);
    }

    protected void alert(@StringRes int msg) {
        mView.alert(msg);
    }

    protected void showProgressDialog(CharSequence msg) {
        mView.showProgressDialog(msg);
    }

    protected void dismissProgressDialog() {
        mView.dismissProgressDialog();
    }

    protected void setProgressMessage(CharSequence msg) {
        mView.setProgressMessage(msg);
    }

    /**
     * 添加订阅
     */
    protected final void addSubscription(Subscription subscription) {
        if (mSubscriptions == null) {
            synchronized (this) {
                if (mSubscriptions == null) {
                    mSubscriptions = new CompositeSubscription();
                }
            }
        }
        mSubscriptions.add(subscription);
    }

    void onViewDestroy() {
        if (useEventBus()) {
            EventBus.getDefault().unregister(this);
        }
        if (mSubscriptions != null) {
            mSubscriptions.unsubscribe();
            mSubscriptions = null;
        }
    }

    void onViewCreate() {
        if (useEventBus()) {
            EventBus.getDefault().register(this);
        }
    }

    protected boolean useEventBus() {
        return false;
    }
}
